<?php

/**
 * 这个示例用来说明异常
 *
 * User: ford
 * Date: 15-8-10
 * Time: 上午11:03
 */

/**
 * 在类中只管定义异常抛出
 * 异常处理应当在类的实现之中
 *
 * Class WriteToFile
 */
class WriteToFile {

	//存储文件指针
	private $_fp = null;

	/**
	 * 初始要类，打开要写入的文件，取得文件指针
	 *
	 * @param $file string 文件名称
	 * @throws Exception
	 */
	function __construct($file) {

		//检查文件是否存在，不存在就抛出异常
		if((!file_exists($file)) || !is_file($file)) {
			throw new Exception('The file does not exist.');

		}
		//检查文件能否以写入方式打开，打开失败将抛出异常
		if(!$this->_fp = @fopen($file, 'w')) {
			throw new Exception('Could not open the file.');
		}
	}

	/**
	 * 写入数据
	 * @param $data string 要写入的数组
	 * @throws Exception
	 */
	function write($data) {
		if(@!fwrite($this->_fp, $data . "\n")) {
			throw new Exception('Could not write to the file.');
		}
	}

	function close() {
		if($this->_fp) {
			fclose($this->_fp);
			$this->_fp = null;
		}
	}

	function __destruct() {
		$this->close();
	}

}

//下面来测试
try {
	$file = new WriteToFile('abc');
	$file->write('用这个来测试一下！');
	$file->close();
	unset($file);
} catch (Exception $e) {
	echo '<p>The process could not be completed because the scripte <strong>' . $e->getMessage() . '</strong></p>';
}